package br.com.edumobi.fragments;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.Date;
import java.util.List;

import br.com.edumobi.R;
import br.com.edumobi.adapters.ListaAlternativasAdapter;
import br.com.edumobi.dados.modelos.Alternativa;
import br.com.edumobi.dados.modelos.Questao;

public class MSQuestaoFragment extends GenericoFragment {

    private ImageView imageViewVoltarListaQuestoesMSQuestaoFragment;
    private TextView textViewTempoCorridoMSQuestaoFragment;
    private TextView textViewNumeroQuestaoMSQuestaoFragment;
    private TextView textViewEnunciadoMSQuestaoFragment;
    private ListView listViewAlternativasMSQuestaoFragment;
    private Button buttonProximaMSQuestaoFragment;

    private AcoesMSQuestaoFragment activity;
    private MSQuestaoTask task;

    private List<Questao> questoes;
    private Integer indexQuestao;
    private Integer sizeQuestoes;
    private Long inicio;
    private Long corrido;

    private AdapterView.OnItemClickListener clickItemlistViewAlternativasMSQuestaoFragment = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            questoes.get(indexQuestao).idAlternativaSelecionada = id;
            buttonProximaMSQuestaoFragment.setBackgroundColor(Color.parseColor("#ff0a8cbf"));
            carregarListViewAlternativas(questoes.get(indexQuestao).alternativas, questoes.get(indexQuestao).idAlternativaSelecionada);
        }
    };

    private View.OnClickListener clickButtonProximaMSQuestaoFragment = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (questoes.get(indexQuestao).idAlternativaSelecionada != null) {

                questoes.get(indexQuestao).respondida = true;
                questoes.get(indexQuestao).acertou = questoes.get(indexQuestao).idAlternativaSelecionada.equals(questoes.get(indexQuestao).alternativaCorreta.id);

                buttonProximaMSQuestaoFragment.setBackgroundColor(Color.parseColor("#ffcdcdcd"));

                indexQuestao = obterIndexProximaQuestao();

                if (indexQuestao != null) {
                    visualizarQuestao(questoes.get(indexQuestao));
                } else {
                    activity.irResultado();
                    pararTask();
                }
            }
        }
    };

    private View.OnClickListener clickImageViewVoltarListaQuestoesMSQuestaoFragment = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            activity.irListaDeQuestoes(prepararIrListaQuestao());
        }
    };

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (AcoesMSQuestaoFragment) getActivity();

        questoes = activity.obterQuestoes();
        sizeQuestoes = questoes.size();

        if (inicio == null) {
            inicio = activity.obterInicio();
            if (inicio != null) {
                corrido = System.currentTimeMillis() - inicio;
            }
        }

        if (task == null || task.getStatus().equals(AsyncTask.Status.FINISHED)) {
            task = new MSQuestaoTask();
            task.execute();
        }

        if (indexQuestao == null) {
            if (activity.obterIndexQuestaoSelecionada() != null) {
                indexQuestao = activity.obterIndexQuestaoSelecionada();
            } else {
                indexQuestao = obterIndexProximaQuestao();
            }
        }

        if (indexQuestao != null) {
            visualizarQuestao(questoes.get(indexQuestao));
        } else {
            visualizarQuestao(questoes.get(0));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ms_questao, container, false);

        imageViewVoltarListaQuestoesMSQuestaoFragment = (ImageView) view.findViewById(R.id.imageViewVoltarListaQuestoesMSQuestaoFragment);
        textViewTempoCorridoMSQuestaoFragment = (TextView) view.findViewById(R.id.textViewTempoCorridoMSQuestaoFragment);
        textViewNumeroQuestaoMSQuestaoFragment = (TextView) view.findViewById(R.id.textViewNumeroQuestaoMSQuestaoFragment);
        textViewEnunciadoMSQuestaoFragment = (TextView) view.findViewById(R.id.textViewEnunciadoMSQuestaoFragment);
        listViewAlternativasMSQuestaoFragment = (ListView) view.findViewById(R.id.listViewAlternativasMSQuestaoFragment);
        buttonProximaMSQuestaoFragment = (Button) view.findViewById(R.id.buttonProximaMSQuestaoFragment);

        imageViewVoltarListaQuestoesMSQuestaoFragment.setOnClickListener(clickImageViewVoltarListaQuestoesMSQuestaoFragment);
        listViewAlternativasMSQuestaoFragment.setOnItemClickListener(clickItemlistViewAlternativasMSQuestaoFragment);
        buttonProximaMSQuestaoFragment.setOnClickListener(clickButtonProximaMSQuestaoFragment);

        return view;
    }

    @Override
    public void exibirComponentes() {
        imageViewVoltarListaQuestoesMSQuestaoFragment.setVisibility(View.VISIBLE);
        textViewTempoCorridoMSQuestaoFragment.setVisibility(View.VISIBLE);
        textViewNumeroQuestaoMSQuestaoFragment.setVisibility(View.VISIBLE);
        textViewEnunciadoMSQuestaoFragment.setVisibility(View.VISIBLE);
        listViewAlternativasMSQuestaoFragment.setVisibility(View.VISIBLE);
        buttonProximaMSQuestaoFragment.setVisibility(View.VISIBLE);
    }

    @Override
    public void esconderComponentes() {
        imageViewVoltarListaQuestoesMSQuestaoFragment.setVisibility(View.GONE);
        textViewTempoCorridoMSQuestaoFragment.setVisibility(View.GONE);
        textViewNumeroQuestaoMSQuestaoFragment.setVisibility(View.GONE);
        textViewEnunciadoMSQuestaoFragment.setVisibility(View.GONE);
        listViewAlternativasMSQuestaoFragment.setVisibility(View.GONE);
        buttonProximaMSQuestaoFragment.setVisibility(View.GONE);
    }

    private void visualizarQuestao(Questao questao) {
        textViewNumeroQuestaoMSQuestaoFragment.setText(String.valueOf(indexQuestao + 1) + "/" + String.valueOf(sizeQuestoes));
        textViewEnunciadoMSQuestaoFragment.setText(questao.enunciado);

        if (questao.idAlternativaSelecionada != null) {
            buttonProximaMSQuestaoFragment.setBackgroundColor(Color.parseColor("#ff0a8cbf"));
        }

        if (corrido != null) {
            textViewTempoCorridoMSQuestaoFragment.setText(String.valueOf(corrido / 60 / 1000) + " min passado(s)");
        } else {
            textViewTempoCorridoMSQuestaoFragment.setText(String.valueOf(0) + " min passado(s)");
        }

        carregarListViewAlternativas(questao.alternativas, questao.idAlternativaSelecionada);
    }

    private void carregarListViewAlternativas(List<Alternativa> alternativas, Long idAlternativaSelecionada) {
        if (idAlternativaSelecionada != null) {
            listViewAlternativasMSQuestaoFragment.setAdapter(new ListaAlternativasAdapter(alternativas, idAlternativaSelecionada));
        } else {
            listViewAlternativasMSQuestaoFragment.setAdapter(new ListaAlternativasAdapter(alternativas));
        }
    }

    private Integer obterIndexProximaQuestao() {
        if (indexQuestao == null) {
            for (int index = 0; index < sizeQuestoes; index++) {
                if (!questoes.get(index).respondida) {
                    return index;
                }
            }
        } else {
            if (indexQuestao + 1 >= sizeQuestoes) {
                for (int index = 0; index < sizeQuestoes; index++) {
                    if (!questoes.get(index).respondida) {
                        return index;
                    }
                }

                return null;
            } else {
                for (int index = 0; index < sizeQuestoes; index++) {
                    if (!questoes.get(index).respondida) {
                        return index;
                    }
                }

                return indexQuestao + 1;
            }
        }

        return null;
    }

    private void pararTask() {
        if (task.getStatus().equals(AsyncTask.Status.RUNNING)) {
            task.cancel(true);
        }
    }

    public Long prepararIrListaQuestao() {
        pararTask();
        return inicio;
    }

    private class MSQuestaoTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            if (inicio == null) {
                inicio = new Date().getTime();
            }

            while (true) {
                corrido = System.currentTimeMillis() - inicio;

                if (corrido.equals(Long.valueOf(activity.obterDuracao().getTime())) || corrido > activity.obterDuracao().getTime()) {
                    break;
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            activity.irResultado();
        }
    }

    public interface AcoesMSQuestaoFragment extends AcoesGenericoFragment {
        List<Questao> obterQuestoes();
        Date obterDuracao();
        Integer obterIndexQuestaoSelecionada();
        Long obterInicio();
        void irListaDeQuestoes(Long inicioSimulado);
        void irResultado();
    }
}